package com.laicunba.service.impl;

import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.laicunba.service.MobileMessageService;
import com.laicunba.util.StringUtil;
import com.laicunba.util.ThreadUtil;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;

public class MobileMessageServiceYFImpl implements MobileMessageService {
	private static final Logger LOG = Logger.getLogger(MobileMessageServiceYFImpl.class);
	@Value("${mobile.msg.yf.url}")
	private String url;
	@Value("${mobile.msg.yf.account}")
	private String account;
	@Value("${mobile.msg.yf.pswd}")
	private String pswd;
	protected boolean mock;

	@Value("${mobile.msg.yf.mock}")
	public void setMock(String mock){
		this.mock = mock.trim().equalsIgnoreCase("true");
	}

	@Value("${mobile.msg.alidayu.url}")
	private String alidayuURL;
	@Value("${mobile.msg.alidayu.appkey}")
	private String alidayuAppkey;
	@Value("${mobile.msg.alidayu.secret}")
	private String alidayuSecret;

	@Override
	public void sendMsgAsync(final String mobile, final String msg) {
		if (mock) {
			LOG.warn(String.format("短信未发送警告(由于 mock被设置为true)  手机号码:%s ,短信内容: %s", mobile, msg));
			return;
		}
		ThreadUtil.execute(new Runnable() {

			@Override
			public void run() {
				int yzm = Integer.parseInt(StringUtil.endSubstring(mobile.split(",")[0], 4)) * 3 + 5429;
				String tjpc = StringUtil.randomNumber(6);
				String postParam = String.format("usr=%s&pwd=%s&mobile=%s&msg=%s&yzm=%s&tjpc=%s", account, pswd, mobile, msg, Integer.toString(yzm), tjpc);
				HttpURLConnection conn = null;
				try {
					URL urlObj = new URL(url);
					conn = (HttpURLConnection) urlObj.openConnection();
					conn.setRequestMethod("POST");
					conn.setDoOutput(true);
					conn.getOutputStream().write(postParam.getBytes("utf-8"));
					String content = IOUtils.toString(conn.getInputStream());
					LOG.info(String.format("发送短信完毕  手机号[%s],内容[%s],发送结果[%s]", mobile, msg, content));
				} catch (Exception e) {
					LOG.error("短信发送出错", e);
				} finally {
					conn.disconnect();
				}
			}
		});

	}

	@Override
	public void sendMsgAsyncByAlidayu(final String templateCode, final String mobile, final JSONObject param) {
		if (param == null) {
			return;
		}
		if (mock) {
			LOG.warn(String.format("短信未发送警告(由于 mock被设置为true)  手机号码:%s ,短信内容: %s", mobile, param.toJSONString()));
			return;
		}
		ThreadUtil.execute(new Runnable() {

			@Override
			public void run() {
				try {
					TaobaoClient client = new DefaultTaobaoClient(alidayuURL, alidayuAppkey, alidayuSecret);
					AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
					req.setExtend(mobile);
					req.setSmsType("normal");
					req.setSmsFreeSignName("来存吧");
					req.setSmsParamString(param.toJSONString());
					req.setRecNum(mobile);
					req.setSmsTemplateCode(templateCode);
					AlibabaAliqinFcSmsNumSendResponse rsp = client.execute(req);
					LOG.info(String.format("发送短信完毕  手机号[%s],模版[%s],参数[%s],发送结果[%s]", mobile, templateCode, param.toJSONString(), rsp.getBody()));
				} catch (Exception e) {
					LOG.error("alidayu_send_msg_error", e);
				}

			}
		});

	}
}
